<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */

if (!defined('IN_QQAS'))
{
	exit('Hacking attempt');
}
// ------------------------------------------------------------------------

/**
 * Cron jobs
 *
 * @category	Action
 */
class CronAction extends Action
{


    //初始化
	public function _initialize()
    {

    }


    //执行计划任务
    public function runCron($cronID=0)
    {
        $Cron = D('Cron');
        $time  = time();
        $cache = F('cache_cron_jobs');
        $jobs = !empty($cronID) ? array($cache[$cronID]) : $cache;

        if (!empty($jobs))
        {
            foreach ($jobs as $value)
            {
                if ($value['next_run_time'] <= $time)
                {
                	if (!empty($value['minute']))
                	{
                	    $minute = intval(gmdate('m', $time));
                		$array = explode(',', $value['minute']);
                		if (!in_array($minute, $array))
                		{
                			continue;
                		}
                	}
                }

                //执行计划任务
                call_user_method($value['method_name'], $this);

                //获取下次执行时间
                $cron = array(
                    'day'     => $value['day'],
                    'weekday' => $value['weekday'],
                    'hour'    => $value['hour'],
                    'minute'  => $value['minute'],
                );
                $next = $this->getNextRunTime($cron);
                $map  = array('cron_id' => $value['cron_id']);
                $data = array(
                    'last_run_time' => $time,
                    'next_run_time' => $next,
                );
                $Cron->where($map)->save($data);
            }

            $Cron->cacheCronJobs();
        }
    }


    //获取计划任务下次执行时间
    private function getNextRunTime($cron)
    {
        $time = time();
        $sy   = $y  = gmdate('Y');
        $smo  = $mo = gmdate('n');
        $sd   = $d  = gmdate('j');
        $w    = gmdate('w', $time);
        $sh   = $m  = 0;
        /*
        $sh   = $h  = gmdate('G');
        $sm   = $m  = gmdate('i');
        */
        if (-1 != $cron['day'])
        {
            $sd = $cron['day'];
            $smo = $mo + 1;
        }
        //选择weekday将覆盖day设置
        if(-1 != $cron['weekday'])
        {
            $sd = $d;
            $smo = $mo;
            if (-1 != $cron['weekday'])
            {
                $sd += $cron['weekday'] - $w + 7;
            }
        }
        if (-1 != $cron['hour'])
        {
            $sh = $cron['hour'];
            if (-1 == $cron['day'] &&  -1 == $cron['weekday'])
            {
                $sd++;
            }
        }
        //限制执行频率半小时以上
        if (-1 == $cron['day'] &&  -1 == $cron['weekday'] && -1 == $cron['hour'])
        {
            $sm += 30;
        }
        $next = gmmktime($sh, $sm, 0, $smo, $sd, $sy);

        return $next < $time ? $time : $next;
    }

    /*---------------------------- cron job details ------------------------------*/

	/**
	 * @desc 日清理
	 *
	 * @access public
	 */
	public function dailyCleanUp()
	{
        $AD = M('Advertisement');
        $map = array(
            'end_time' => array('gt', 0),
            'end_time' => array('lt', time()),
        );
        $data = array('status' => 0);
        $AD->where($map)->save($data);
        cache_advertisements();
	}


	/**
	 * @desc 回收过期徽章(频率/每天)
	 *
	 * @access public
	 */
	public function dailyRevokeExpiredMedal()
	{
	    $User = M('User');
	    $time = time();

	    $prefix = C('DB_PREFIX');
	    $sql  = " SELECT U.user_id,U.medal,L.medal_id From {$prefix}medal_log L LEFT JOIN {$prefix}User U ";
        $sql .= " ON L.user_id=U.user_id WHERE expire_time> 0 AND expire_time < {$time} ";
        $results = M()->query($sql);

        if (!empty($results))
        {
        	foreach ($results as $value)
        	{
                if (!empty($value['medal']))
                {
                    $medal = explode(',', $value['medal']);
                    $key = array_search($value['medal_id'], $medal);
                    unset($medal[$key]);
                    $data = array('medal' => implode(',', $medal));
                    $where = array('user_id' => $value['user_id']);
                    $User->where($where)->save($data);
                }
        	}
        }
	}


	/**
	 * @desc 清理在线过期会员
     *
	 * @access public
	 */
	public function  clearExpiredOnlineUsers()
	{
	    $time = time();
	    $online_hold_time = intval(get_site_config('online_hold_time'));
		$online_hold_time = $online_hold_time ? 60 * $online_hold_time : 1800;
		$map = array(
			'last_activity' => array('lt', $time - $online_hold_time),
		);
		$Model->where($map)->delete();
	}


	/**
	 * @desc 发送生日祝福邮件(频率/每天)
	 *
	 * @access public
	 */
	public function dailyBirthdayWishes()
	{
		import('ORG.Net.Http');

	    $User = M('User');

	    $date  = date('m-d', (time() - 86400));
	    $where = "DATE_FORMAT(birthday,'%m-%d')='{$date}'";
	    $field = array('user_id','username','email');
	    $users = $User->field($field)->where($where)->select();

	    if (!empty($users))
	    {
	    	foreach ($users as $user)
	    	{
	    		$requestUrl = get_site_domain(). U('Home-Ajax/sendBirthdayWishes', array('uid' => $user['user_id']));
				Http::async_request($requestUrl);
	    	}
	    }
	}

}
// End  Class

/* End of file CronAction.class.php */
/* Location: ./App/Lib/Action/CronAction.class.php */